package com.weifei.core.mvc;

import com.weifei.core.anotation.*;
import com.weifei.core.ioc.WFApplicationContext;
import com.weifei.core.mvc.DispatcherHandler;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WFDispatcherServlet extends HttpServlet {
    private Map<String, Object> ioc = new ConcurrentHashMap<>();
    private Map<String, Method> handlerMapping = new ConcurrentHashMap<>();
    private List<DispatcherHandler> handlerList = new ArrayList<DispatcherHandler>();
    private Map<String, String> paramters = new ConcurrentHashMap<>();
    private Properties configContext = new Properties();

    //进一步改造
    private final String LOCATION = "contextConfigLocation";
    private List<WFHandlerMapping> handlerMappings = new ArrayList<>();
    private Map<WFHandlerMapping, WFHandlerAdapter> handlerAdapters = new ConcurrentHashMap<>();
    private WFApplicationContext applicationContext;
    private List<WFViewResolver> viewResolvers = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatch(req, resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatch(req, resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatch(req, resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatch(req, resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 分发请求
     * @param request
     * @param response
     */
    private void doDispatch(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException {

        WFHandlerMapping handler = this.getHandler(request);
        if (handler == null) {
            response.getWriter().write("404 not found page...");
            return;
        }
        WFHandlerAdapter adapter = this.getHandlerAdapter(handler);

        WFModelAndView modelAndView = adapter.handler(request, response, handler);

        this.processDispatchResult(request, response, modelAndView);

        return;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            applicationContext = new WFApplicationContext(
                    config.getInitParameter(LOCATION));
            this.initStrategies(applicationContext);


            System.out.println("ioc init completed..");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }

    private void initStrategies(WFApplicationContext context) throws Exception {
        this.initHandlerMappings(context);
        this.initHandlerAdapters(context);
        this.initViewResolvers(context);
    }

    /**
     * 构建Controller中配置的requestMapping和Method的映射关系
     * @param context
     */
    private void initHandlerMappings(WFApplicationContext context) throws Exception {
        String[] beanNames = context.getBeanDefinitionNames();
        for (String beanName :beanNames) {
            Object object = context.getBean(beanName);
            if (object == null) {
                continue;
            }
            Class clazz = object.getClass();
            if (!clazz.isAnnotationPresent(WFController.class)) {
                continue;
            }
            String baseUrl = "";
            if (clazz.isAnnotationPresent(WFRequestMapping.class)) {
                WFRequestMapping requestMapping = (WFRequestMapping) clazz.getAnnotation(WFRequestMapping.class);
                baseUrl = requestMapping.value();
            }
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(WFRequestMapping.class)) {
                    continue;
                }
                WFRequestMapping mapping = method.getAnnotation(WFRequestMapping.class);
                String regex = ("/" + baseUrl + mapping.value()).replaceAll("\\*", ".*")
                        .replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                this.handlerMappings.add(new WFHandlerMapping(object, method, pattern));
            }

        }
    }


    private void initHandlerAdapters(WFApplicationContext context) {
        for (WFHandlerMapping mapping : handlerMappings) {
            this.handlerAdapters.put(mapping, new WFHandlerAdapter());
        }
    }
    /**
     * 解决页面名字和模板文件的关联问题
     * @param context
     */
    private void initViewResolvers(WFApplicationContext context) {
        String templateRoot = context.getConfig().getProperty("templateRoot");
        String templatePath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
        File templateRootDir = new File(templatePath);
        for (File template : templateRootDir.listFiles()) {
            WFViewResolver resolver = new WFViewResolver(templatePath);
            if (!"".equals(context.getConfig().getProperty("templateSuffix"))) {
                resolver.setTemplateSuffix(context.getConfig().getProperty("templateSuffix"));
            }
            this.viewResolvers.add(resolver);
        }
    }

    private WFHandlerAdapter getHandlerAdapter(WFHandlerMapping handler) {
        if (this.handlerAdapters.isEmpty()) {
            return null;
        }
        WFHandlerAdapter adapter = this.handlerAdapters.get(handler);
        if (adapter.support(handler)) {
            return adapter;
        }
        return null;
    }
    private WFHandlerMapping getHandler(HttpServletRequest request) {
        if (this.handlerMappings.isEmpty()) {
            return null;
        }
        String url = request.getRequestURI();
        String contextPath = request.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+","/");
        for (WFHandlerMapping handler : this.handlerMappings) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

    private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, WFModelAndView mv) throws IOException {
        if (mv == null) {
            return;
        }
        if (this.viewResolvers.isEmpty()) {
            return;
        }
        if (this.viewResolvers != null) {
            for (WFViewResolver resolver : viewResolvers) {
                WFView view = resolver.resolveView(mv.getViewName(), null);
                if (view != null) {
                    view.render(mv.getModel(), request, response);
                    return;
                }
            }
        }


    }

}
